'use strict';

const _ = require('lodash');
const utility = require('utility');
const validator = require('validator');
const Controller = require('egg').Controller;

class CustomizeController extends Controller {

  async toCustomize() {
    const user = this.ctx.user;
    let show_list = [];
    let locals = {show_list};
    if (user) {
      let query_list = await this.ctx.service.customizeSvc.list(user.id);
      for (const v of query_list) {
        let item = {
          avatar_url: v.avatar_url,
          inner_url: v.inner_url,
          id: v._id,
          status: v.status,
        };

        if (v.type == 'extract') {
          item.type = '智能订阅';
          item.show_name = v.extract_url;
          if (v.extract_board) {
            item.show_name += ' ' + v.extract_board;
          }
        } else if (v.type == 'weixin') {
          item.type = '公众号订阅';
          item.show_name = v.weixin_name;
        } else if (v.type == 'rss') {
          item.type = 'RSS订阅';
          item.show_name = v.rss_url;
        }
        show_list.push(item);
      }
    }
    return await this.ctx.renderX('user/customize.nj', locals);
  }

  async customize() {
    let customize = this.ctx.request.body;
    const user = this.ctx.user;
    if (!user) {
      this.ctx.body = {status: 'failed', error_msg: '请先登录'}
      return;
    }
    customize.user_id = user.id;
    this.logger.info('有新的自定义订阅:', customize);
    await this.ctx.service.customizeSvc.add(customize);

    let manager_id = '5c7cd4f781c857816114c940';
    await this.ctx.service.messageSvc.sendCustomizeMessage(manager_id, user.id);
    await this.ctx.helper.dd_customize(user.loginname);
    this.ctx.body = {status: 'success'};
  }


  async delete() {
    let id = this.ctx.params.id;
    const user = this.ctx.user;
    if (!user) {
      this.ctx.body = {status: 'failed', error_msg: '请先登录'};
      return;
    }
    this.logger.info('删除自定义订阅:', id, user.id);
    let result = await this.ctx.service.customizeSvc.delete(id, user.id);
    if (result == 1) {
      return this.ctx.redirect('/customize');
    } else {
      this.ctx.body = {status: 'failed', error_msg: '删除失败'};
    }
  }
}

module.exports = CustomizeController;
